<?php

declare(strict_types=1);

namespace app\api\controller;

use app\common\model\User;
use app\common\tool\Result;
use addons\WeChatMini\facade\WeChatMini;
use think\exception\ValidateException;

class Login extends Base
{
    /**
     * 手机号授权登录
     */
    public function miniAppletLogin()
    {
        try {
            $param = $this->request->post();
            $this->validate($param, 'MiniAppletLogin');
            $phone = WeChatMini::getUserInfo($param['code'], $param['iv'], $param['encryptedData']);
            if (!empty($phone)) {
                $param['mobile'] = $phone['phoneNumber'];
                $param['openid'] = $phone['openid'];
                return Result::fastReturn(User::_miniAppletSave($param));
            } else {
                return Result::fail('请重新获取授权！');
            }
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        }
    }
    /**
     * 普通授权登录
     */
    public function miniLogin()
    {
        try {
            $param = $this->request->post();
            $this->validate($param, 'MiniAppletLogin');
            $phone = WeChatMini::session($param['code']);
            if (!empty($phone)) {
                $param['openid'] = $phone['openid'];
                return Result::fastReturn(User::_miniLogin($param));
            } else {
                return Result::fail('请重新获取授权！');
            }
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        }
    }
}
